import Vue from 'vue';
import { login, getInfo, logout } from '@/api/login-api';
import { ACCESS_TOKEN } from '@/store/mutation-types';
import { welcome } from '@/utils/index';

const user = {
  namespaced: true,
  state: {
    token: '',
    name: '',
    welcome: '',
    avatar: '',
    roles: [],
    info: {}
  },

  mutations: {
    SET_TOKEN: (state, token) => {
      state.token = token;
    },
    SET_NAME: (state, { name, welcome }) => {
      state.name = name;
      state.welcome = welcome;
    },
    SET_AVATAR: (state, avatar) => {
      state.avatar = avatar;
    },
    SET_ROLES: (state, roles) => {
      state.roles = roles;
    },
    SET_INFO: (state, info) => {
      state.info = info;
    }
  },

  actions: {
    // 登录
    login({ commit }, userInfo) {
      return new Promise((resolve, reject) => {
        login(userInfo).then(result => {
          Vue.ls.set(ACCESS_TOKEN, result.token, new Date().getTime() + 7 * 24 * 60 * 60 * 1000);
          commit('SET_TOKEN', result.token);
          resolve(result);
        }).catch(error => {
          reject(error);
        });
      });
    },

    // 获取用户信息
    getInfo({ commit }) {
      return new Promise((resolve, reject) => {
        // 请求后端获取用户信息 /api/user/info
        getInfo().then(result => {
          console.log(result);
          if (!result) return reject(new Error('getInfo: roles must be a non-null array !'));

          const role = { ...result.role };
          role.permissions = result.role.permissions.map(permission => {
            return {
              ...permission,
              actionList: (permission.actionEntitySet || {}).map(item => item.action)
            };
          });
          role.permissionList = role.permissions.map(permission => permission.permissionId);
          // 覆盖响应体的 role, 供下游使用
          result.role = role;

          console.log('role', role);

          commit('SET_ROLES', role);
          commit('SET_INFO', result);
          commit('SET_NAME', { name: result.name || result.username, welcome: welcome() });
          commit('SET_AVATAR', result.avatar);
          // 下游
          resolve(result);
        }).catch(error => {
          reject(error);
        });
      });
    },

    // 登出
    logout({ commit, state }) {
      return new Promise((resolve) => {
        logout(state.token).then(() => {
          commit('SET_TOKEN', '');
          commit('SET_ROLES', []);
          Vue.ls.remove(ACCESS_TOKEN);
          resolve();
        }).catch((err) => {
          console.log('logout fail:', err);
          // resolve()
        }).finally(() => {
        });
      });
    }

  }
};

export default user;
